package shop.core.task;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import shop.services.front.plot.PlotService;
import shop.services.front.plot.bean.Plot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created by wzl on 2018/1/3.
 */
@Component
public class InsertDataTask implements Runnable {
    @Autowired
    private PlotService plotService;

    @Override
    public void run() {
        Plot plot = new Plot();
        List<Plot> plotList=plotService.selectList(plot);
        for(Plot plotInfo: plotList){
            String address=plotInfo.getProvince()+plotInfo.getCity()+plotInfo.getArea()+plotInfo.getName();
            BufferedReader in = null;
            try {
                address = URLEncoder.encode(address, "UTF-8");
                URL tirc = new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+"7d9fbeb43e975cd1e9477a7e5d5e192a");
                in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));
                String res;
                StringBuilder sb = new StringBuilder("");
                while((res = in.readLine())!=null){
                    sb.append(res.trim());
                }
                String str = sb.toString();
                if(StringUtils.isNotEmpty(str)){
                    int lngStart = str.indexOf("lng\":");
                    int lngEnd = str.indexOf(",\"lat");
                    int latEnd = str.indexOf("},\"precise");
                    if(lngStart > 0 && lngEnd > 0 && latEnd > 0){
                        String lng = str.substring(lngStart+5, lngEnd);
                        String lat = str.substring(lngEnd+7, latEnd);
                        plotInfo.setLng(lng);
                        plotInfo.setLat(lat);
                        plotService.update(plotInfo);
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
